package com.framework.auth.config;

import com.framework.auth.interceptor.AuthInterceptor;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ConditionalOnMissingBean(AuthConfig.class)
public class AuthAutoConfiguration implements WebMvcConfigurer {

    private final ApplicationContext applicationContext;

    // 构造器注入 ApplicationContext
    public AuthAutoConfiguration(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public AuthConfig authConfig() throws Exception {
        return new AuthConfig();
    }

    @Bean
    public AuthInterceptor authInterceptor(AuthConfig authConfig) {
        // 通过构造器将 applicationContext 传递给 AuthInterceptor
        return new AuthInterceptor(authConfig, applicationContext);
    }

    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        try {
            // 注册拦截器，并配置所有请求都经过拦截器
            registry.addInterceptor(authInterceptor(authConfig()))
                    .addPathPatterns("/**"); // 配置所有请求都经过拦截器
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
